Implement a Program to Demonstrate Exception Handling using `try`, `catch`, and `throw` in C++
In C++, exception handling is a powerful mechanism to manage runtime errors and ensure that your program does not crash unexpectedly. It allows the program to gracefully handle abnormal situations such as divide-by-zero errors, invalid inputs, file access failures, and so on.
The three core components of exception handling in C++ are:
- `try` block: The code that may potentially cause an exception.
- `throw` statement: Used to signal (or throw) an exception.
- `catch` block: Catches and handles the exception thrown.
🎯 Why Use Exception Handling?
- Improves program stability.
- Helps to separate error-handling logic from normal code.
- Makes the code easier to read and maintain.
- Prevents crashes and provides user-friendly error messages.
🧑💻 C++ Program: Demonstrate Exception Handling
Let’s write a simple C++ program that divides two numbers and uses exception handling to catch division by zero.
#include <iostream>
using namespace std;
int divide(int a, int b) {
if (b == 0) {
throw "Division by zero error!";
}
return a / b;
}
int main() {
int num1, num2;
cout << "Enter two integers: ";
cin >> num1 >> num2;
try {
int result = divide(num1, num2);
cout << "Result of division: " << result << endl;
} catch (const char* msg) {
cout << "Exception caught: " << msg << endl;
}
cout << "Program continues after exception handling." << endl;
return 0;
}
🖨️ Sample Output
Enter two integers: 10 0
Exception caught: Division by zero error!
Program continues after exception handling.
🔍 Explanation of the Code
- Function `divide(int a, int b)` checks if the denominator `b` is zero.
- If zero, it throws a string literal as an exception.
- The `try` block in `main()` attempts to perform the division.
- The `catch` block intercepts the exception and displays a user-friendly message.
- Regardless of the error, the program continues execution after handling the exception.
🔄 Types of Throwables in C++
C++ allows throwing:
- Built-in types: `int`, `char`, `const char*`, etc.
- Objects of classes: For advanced error handling using custom exception classes.
- Standard exceptions: Like `std::exception`, `std::runtime_error`, etc. (from `<stdexcept>`)
📌 Best Practices in Exception Handling
- Use specific `catch` blocks for different exception types.
- Avoid catching all exceptions with a blank `catch(...)` unless necessary.
- Use exception handling only for **exceptional conditions**, not for normal control flow.
- Always handle exceptions gracefully and log errors if needed.
📝 Conclusion
Exception handling in C++ using `try`, `catch`, and `throw` is a vital feature for writing **robust and error-resilient applications**. Whether you're performing file operations, mathematical computations, or complex input validations, exception handling makes your code safer and more reliable.
Comments
Post a Comment